package kr.hkit.androidcomplete02.ch19;

import kr.hkit.androidcomplete02.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

public class LongTime4 extends Activity {
	int mainValue;
	TextView tv;
	boolean mQuit;
	ProgressDialog mProgress;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch19_uploadex);
		
		tv = (TextView) findViewById(R.id.ch19_uploadex_tv);
	}
	
	public void mOnClick(View v){
		mProgress = new ProgressDialog(this);
		mProgress.setTitle("Updating");
		mProgress.setMessage("Wait...");
		mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		mProgress.setOnCancelListener(new OnCancelListener() {
			public void onCancel(DialogInterface dialog) {
				mQuit = true;
				mProgress.dismiss();
			}
		});
		mProgress.show();
		mQuit = false;
		
		if(mainValue >= 100) mainValue = 0;
		UpdateThread mThread = new UpdateThread(mainValue);
		mThread.start();
	}
	
	Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			int mValue = msg.arg1;
			mainValue = mValue;
			
			if(mValue <= 100 && mQuit == false){
				tv.setText(Integer.toString(mValue));
				mProgress.setProgress(mValue);
			} else {
				mQuit = true;
				mProgress.dismiss();
			}
		};
	};
	
	class UpdateThread extends Thread{
		int mValue;

		public UpdateThread(int mValue) {
			super();
			this.mValue = mValue;
		}

		public void run() {
			while(mQuit == false){
				mValue++;
				Message msg = mHandler.obtainMessage(0, mValue, 0);
				mHandler.sendMessage(msg);
				
				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}